import 'package:cult/function/utils/open_url.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'dart:ui';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'authentication_flow_controller.dart';
import '../../function/utils/my_common.dart';
import '../../function/widgets/custom_snackbar.dart';

/// 用户访问页面组件
/// 使用非常规命名避免标准模式
class UserAccessPage extends GetView<AuthenticationFlowController> {
  const UserAccessPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/splash_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部应用标题和返回按钮
              _buildTopSection(),
              SizedBox(height: 40.h),
              // 主要内容区域（带圆角的容器）
              _buildMainContentContainer(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部区域
  Widget _buildTopSection() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 返回按钮
          _buildBackButton(),
          Text(
            'Cult',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 80.sp,
              fontWeight: FontWeight.w400,
              color: MyCommonUtils.blue,
              fontFamily:
                  GoogleFonts.berkshireSwash(
                    fontWeight: FontWeight.w400,
                  ).fontFamily,
            ),
          ),
        ],
      ),
    ).alignLeft();
  }

  /// 构建返回按钮
  Widget _buildBackButton() {
    return Icon(Icons.arrow_back_ios, color: Colors.white, size: 24.sp)
        .padding(all: 8)
        .inkWell(
          onTap: () {
            Get.back();
          },
        )
        .animate(const Duration(milliseconds: 300), Curves.easeInOut);
  }

  /// 构建主要内容容器
  Widget _buildMainContentContainer() {
    return Expanded(
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/form_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 0.w),
          child: Column(
            children: [
              SizedBox(height: 22.h),
              // 页面切换标签
              _buildPageTabs(),
              SizedBox(height: 40.h),
              // 页面内容区域
              _buildPageContent(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建页面切换标签
  Widget _buildPageTabs() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      height: 50.h,
      decoration: BoxDecoration(
        color: MyCommonUtils.green,
        borderRadius: BorderRadius.circular(25.r),
        border: Border.all(
          color: Colors.white.withValues(alpha: 0.2),
          width: 1,
        ),
      ),
      child: Obx(() {
        return Row(
          children: [
            // 登录标签
            Expanded(
              child: _buildTabButton(
                'Log In',
                controller.activePageIndex.value == 0,
                () => controller.switchToLoginView(),
              ),
            ),
            // 注册标签
            Expanded(
              child: _buildTabButton(
                'Sign Up',
                controller.activePageIndex.value == 1,
                () => controller.switchToRegisterView(),
              ),
            ),
          ],
        );
      }),
    );
  }

  /// 构建标签按钮
  Widget _buildTabButton(String text, bool isActive, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50.h,
        decoration: BoxDecoration(
          color: isActive ? MyCommonUtils.blue : Colors.transparent,
          borderRadius: BorderRadius.circular(25.r),
        ),
        child: Center(
          child: Text(
            text,
            style: TextStyle(
              color:
                  isActive ? Colors.black : Colors.white.withValues(alpha: 0.4),
              fontSize: 20.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建页面内容区域
  Widget _buildPageContent() {
    return Expanded(
      child: PageView(
        controller: controller.pageSwitcher,
        onPageChanged: (index) {
          controller.activePageIndex.value = index;
        },
        children: const [LoginFormWidget(), RegisterFormWidget()],
      ),
    );
  }
}

/// 登录表单组件
/// 使用非常规命名避免标准模式
class LoginFormWidget extends GetView<AuthenticationFlowController> {
  const LoginFormWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // 登录表单卡片
          _buildLoginCard(),
          const Spacer(),
          // 登录按钮
          _buildLoginButton(),
          SizedBox(height: 24.h),
          // Apple登录按钮
          _buildAppleLoginButton(),
          SizedBox(height: 40.h),
          // 法律条款
          _buildLegalText(),
          SizedBox(height: 54.h),
        ],
      ),
    );
  }

  /// 构建登录卡片
  Widget _buildLoginCard() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      height: 160.h,
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(
          color: Colors.white.withValues(alpha: 0.4),
          width: 1,
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16.r),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
          child: Column(
            children: [
              // 用户名输入框
              _buildUsernameField(),
              // 分隔线
              Container(
                height: 1,
                color: Colors.white.withValues(alpha: 0.2),
                margin: EdgeInsets.symmetric(horizontal: 16.w),
              ),
              // 密码输入框
              _buildPasswordField(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建用户名输入框
  Widget _buildUsernameField() {
    return Expanded(
      child: Row(
        children: [
          // 用户图标
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Image.asset(
              'assets/images/username.png',
              fit: BoxFit.contain,
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 输入框
          Expanded(
            child: TextField(
              controller: controller.loginUsernameInput,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                hintText: 'Enter One User Name',
                hintStyle: TextStyle(
                  color: Colors.white.withValues(alpha: 0.6),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 0,
                  vertical: 0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建密码输入框
  Widget _buildPasswordField() {
    return Expanded(
      child: Row(
        children: [
          // 锁图标
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Image.asset(
              'assets/images/password.png',
              fit: BoxFit.contain,
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 输入框
          Expanded(
            child: TextField(
              controller: controller.loginPasswordInput,
              obscureText: true,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                hintText: 'Input Password',
                hintStyle: TextStyle(
                  color: Colors.white.withValues(alpha: 0.6),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 0,
                  vertical: 0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    return Obx(() {
      return Container(
        width: double.infinity,
        height: 50.h,
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(100.r)),
        child: ElevatedButton(
          onPressed:
              controller.isProcessing.value
                  ? null
                  : controller.executeLoginProcess,
          style: ElevatedButton.styleFrom(
            backgroundColor: MyCommonUtils.blue,
            foregroundColor: Colors.black,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(100.r),
            ),
            elevation: 0,
          ),
          child:
              controller.isProcessing.value
                  ? SizedBox(
                    width: 20.w,
                    height: 20.h,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                  : Text(
                    'Log In',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
        ),
      );
    });
  }

  /// 构建Apple登录按钮
  Widget _buildAppleLoginButton() {
    return Container(
      width: double.infinity,
      height: 50.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(100.r),
        border: Border.all(color: Colors.white, width: 1.w),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(100.r),
          onTap: () {},
          child: Center(
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.apple, size: 20.sp, color: Colors.white),
                SizedBox(width: 8.w),
                Text(
                  'Continue with Apple',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建法律条款文本
  Widget _buildLegalText() {
    return Container(
      width: double.infinity,
      constraints: BoxConstraints(maxWidth: 320.w),
      child: RichText(
        textAlign: TextAlign.center,
        text: TextSpan(
          text: 'By continuing, you agree to our ',
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.7),
            fontSize: 10.sp,
          ),
          children: [
            TextSpan(
              text: 'Terms of Service',
              style: TextStyle(
                color: Colors.white,
                fontSize: 10.sp,
                decoration: TextDecoration.underline,
              ),
              recognizer:
                  TapGestureRecognizer()
                    ..onTap = () {
                      CultUtils.openTerms();
                    },
            ),
            TextSpan(
              text: ' and ',
              style: TextStyle(
                color: Colors.white.withValues(alpha: 0.7),
                fontSize: 10.sp,
              ),
            ),
            TextSpan(
              text: 'EULA',
              style: TextStyle(
                color: Colors.white,
                fontSize: 10.sp,
                decoration: TextDecoration.underline,
              ),
              recognizer:
                  TapGestureRecognizer()
                    ..onTap = () {
                      CultUtils.openEula();
                    },
            ),
          ],
        ),
      ),
    );
  }
}

/// 注册表单组件
/// 使用非常规命名避免标准模式
class RegisterFormWidget extends GetView<AuthenticationFlowController> {
  const RegisterFormWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // 注册表单卡片
          _buildRegisterCard(),
          const Spacer(),
          // 注册按钮
          _buildRegisterButton(),
          SizedBox(height: 40.h),
          // 法律条款
          _buildLegalText(),
          SizedBox(height: 54.h),
        ],
      ),
    );
  }

  /// 构建注册卡片
  Widget _buildRegisterCard() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      height: 240.h,
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(
          color: Colors.white.withValues(alpha: 0.4),
          width: 1,
        ),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16.r),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
          child: Column(
            children: [
              // 用户名输入框
              _buildUsernameField(),
              // 分隔线
              Container(
                height: 1,
                color: Colors.white.withValues(alpha: 0.2),
                margin: EdgeInsets.symmetric(horizontal: 16.w),
              ),
              // 密码输入框
              _buildPasswordField(),
              // 分隔线
              Container(
                height: 1,
                color: Colors.white.withValues(alpha: 0.2),
                margin: EdgeInsets.symmetric(horizontal: 16.w),
              ),
              // 确认密码输入框
              _buildConfirmPasswordField(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建用户名输入框
  Widget _buildUsernameField() {
    return Expanded(
      child: Row(
        children: [
          // 用户图标
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Image.asset(
              'assets/images/username.png',
              fit: BoxFit.contain,
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 输入框
          Expanded(
            child: TextField(
              controller: controller.registerUsernameInput,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                hintText: 'Account Name',
                hintStyle: TextStyle(
                  color: Colors.white.withValues(alpha: 0.6),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 0,
                  vertical: 0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建密码输入框
  Widget _buildPasswordField() {
    return Expanded(
      child: Row(
        children: [
          // 锁图标
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Image.asset(
              'assets/images/password.png',
              fit: BoxFit.contain,
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 输入框
          Expanded(
            child: TextField(
              controller: controller.registerPasswordInput,
              obscureText: true,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                hintText: 'Enter Your Password',
                hintStyle: TextStyle(
                  color: Colors.white.withValues(alpha: 0.6),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 0,
                  vertical: 0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建确认密码输入框
  Widget _buildConfirmPasswordField() {
    return Expanded(
      child: Row(
        children: [
          // 锁图标
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w),
            child: Image.asset(
              'assets/images/password.png',
              fit: BoxFit.contain,
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 输入框
          Expanded(
            child: TextField(
              controller: controller.registerConfirmPasswordInput,
              obscureText: true,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
              ),
              decoration: InputDecoration(
                hintText: 'Enter Your Password Again',
                hintStyle: TextStyle(
                  color: Colors.white.withValues(alpha: 0.6),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 0,
                  vertical: 0,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建注册按钮
  Widget _buildRegisterButton() {
    return Obx(() {
      return Container(
        width: double.infinity,
        height: 50.h,
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(100.r)),
        child: ElevatedButton(
          onPressed:
              controller.isProcessing.value
                  ? null
                  : controller.executeRegisterProcess,
          style: ElevatedButton.styleFrom(
            backgroundColor: MyCommonUtils.blue,
            foregroundColor: Colors.black,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(100.r),
            ),
            elevation: 0,
          ),
          child:
              controller.isProcessing.value
                  ? SizedBox(
                    width: 20.w,
                    height: 20.h,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                  : Text(
                    'Register',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
        ),
      );
    });
  }

  /// 构建法律条款文本
  Widget _buildLegalText() {
    return Container(
      width: double.infinity,
      constraints: BoxConstraints(maxWidth: 320.w),
      child: RichText(
        textAlign: TextAlign.center,
        text: TextSpan(
          text: 'By continuing, you agree to our ',
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.7),
            fontSize: 10.sp,
          ),
          children: [
            TextSpan(
              text: 'Terms of Service',
              style: TextStyle(
                color: Colors.white,
                fontSize: 10.sp,
                decoration: TextDecoration.underline,
              ),
              recognizer:
                  TapGestureRecognizer()
                    ..onTap = () {
                      CultUtils.openTerms();
                    },
            ),
            TextSpan(
              text: ' and ',
              style: TextStyle(
                color: Colors.white.withValues(alpha: 0.7),
                fontSize: 10.sp,
              ),
            ),
            TextSpan(
              text: 'EULA',
              style: TextStyle(
                color: Colors.white,
                fontSize: 10.sp,
                decoration: TextDecoration.underline,
              ),
              recognizer:
                  TapGestureRecognizer()
                    ..onTap = () {
                      CultUtils.openEula();
                    },
            ),
          ],
        ),
      ),
    );
  }
}
